package stanford.com.balldating;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cz.msebera.android.httpclient.Header;
import stanford.com.balldating.chat.ChatActivity;
import stanford.com.balldating.util.*;

public class Main2Activity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private ViewPager mPager;
    private List<View> listViews;
    private List<String> list_title;
    private viewAdapter vAdapter;
    TabLayout tab;
    MyPagerAdapter adapter;
    LayoutInflater mInflater;

    FriendsListAdapter friendsListAdapter;
    ListView friendsListView;

    LiveListAdapter liveListAdapter;
    ListView liveListView;

    View layout_friend;
    View layout_live;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Bmob.initialize(this, "87e563b7c9641d8d10cb9990943a4009");
        Log.i("Viewpage", "--onCreate--");
        initPageView();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        friendsListView=(ListView)layout_friend.findViewById(R.id.friend_lv);
        liveListView = (ListView)layout_live.findViewById(R.id.live_lv);

        friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                User friend=friendsListAdapter.getItem(position);
                Intent intent=new Intent(Main2Activity.this, ChatActivity.class);
                intent.putExtra("friend",friend);
                startActivity(intent);
            }
        });
        liveListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0){
                    Intent intent = new Intent(Main2Activity.this, LiveActivity.class);
                    startActivity(intent);
                }else {
                    User friend = liveListAdapter.getItem(position);
                    Intent intent = new Intent(Main2Activity.this, VideoActivity.class);
                    intent.putExtra("name", friend.getname());
                    startActivity(intent);
                }
            }
        });
        initFriendsListView();
    }

    public void initFriendsListView(){
        RequestParams params=new RequestParams();
        params.add("username", UserUtils.getUser().getname());
        HttpClientUtils.post("/friend/loadFriends", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int i, Header[] headers, String responseString) {
                List<User> friends = new ArrayList<User>();
                List<User> lives= new ArrayList<User>();
                User myLive = new User();
                myLive.setname("我");
                lives.add(myLive);

                try {
                    JSONObject json = new JSONObject(responseString);
                    boolean success = json.getBoolean("success");
                    if (success) {
                        JSONArray datas = json.getJSONArray("data");
                        for (int index = 0; index < datas.length(); index++) {
                            JSONObject data=datas.getJSONObject(index);
                            User user = null;
                            if(!data.getJSONObject("add").getString("username").equals(UserUtils.getUser().getname())){
                                user=new User(data.getJSONObject("add"));
                            }else{
                                user=new User(data.getJSONObject("beAdded"));
                            }
                            friends.add(user);
                            lives.add(user);
                        }


                        friendsListAdapter = new FriendsListAdapter(Main2Activity.this, friends);
                        friendsListView.setAdapter(friendsListAdapter);

                        liveListAdapter = new LiveListAdapter(Main2Activity.this, lives);
                        liveListView.setAdapter(liveListAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement


        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private void initPageView() {
        list_title = new ArrayList<>();
        list_title.add("约球");
        list_title.add("通讯录");
        list_title.add("发现");
        list_title.add("直播间");
        tab = (TabLayout) findViewById(R.id.tabtitle);
        mInflater = getLayoutInflater();
        listViews = new ArrayList<View>();
        listViews.add(mInflater.inflate(R.layout.layout1, null));
        layout_friend=mInflater.inflate(R.layout.layout2, null);
        listViews.add(layout_friend);
        listViews.add(mInflater.inflate(R.layout.layout3, null));
        layout_live = mInflater.inflate(R.layout.layout4,null);
        listViews.add(layout_live);
        adapter = new MyPagerAdapter(listViews);
        mPager = (ViewPager) findViewById(R.id.page);
        mPager.setAdapter(adapter);
        mPager.setCurrentItem(0);
        vAdapter = new viewAdapter(this,listViews,list_title,null);
        tab.setupWithViewPager(mPager);
        tab.getTabAt(0).setText(list_title.get(0));
        tab.getTabAt(1).setText(list_title.get(1));
        tab.getTabAt(2).setText(list_title.get(2));
        tab.getTabAt(3).setText(list_title.get(3));

    }

    public class MyPagerAdapter extends PagerAdapter{
        public List<View> mListViews;
        public View v1;
        public View v2;
        public View v3;


        public MyPagerAdapter(List<View> mListViews) {
            this.mListViews = mListViews;
        }

        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(mListViews.get(arg1));
        }

        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return mListViews.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
            return mListViews.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }

    public void gotoFootball(View view)
    {
        Intent it=new Intent(this,FootballActivity.class);
        startActivity(it);
    }

    public void gotovolleyball(View view)
    {
        Intent it=new Intent(this,VolleyballActivity.class);
        startActivity(it);
    }

    public void gotoLive(View view){
        //Intent it=new Intent(this, LiveListActivity.class);
        //startActivity(it);
    }
}
